<template>
  <div class="margin-container-list">
    <div class="bg-color-white">
      <!--出入库单状态切换 tab -->
      <div class="tabs-box mar-t-20">
        <el-tabs v-model="tabActiveStatus" @tab-click="doChangeTab">
          <el-tab-pane label="已授权商品" name="1"></el-tab-pane>
          <el-tab-pane label="待补货商品" name="2" v-if="warehouse.warehouseType !== 4"></el-tab-pane>
          <el-tab-pane label="已取消授权商品" name="0"></el-tab-pane>
        </el-tabs>
      </div>

      <!-- 顶部搜索 -->
      <div class="mar-b-20">
        <div class="inline-flex">
          <el-select v-model="textCol" class="width-150">
            <el-option label="商品名称" value="title"></el-option>
            <el-option label="商品货号" value="goodsCode"></el-option>
            <el-option label="商品条码" value="goodsBarCode"></el-option>
            <el-option label="外部编码" value="externalCode"></el-option>
            <el-option label="第三方仓库编码" value="thirdSkuCode"></el-option>
          </el-select>
          <el-input @keyup.enter.native="doSearch" v-model.trim="textValue" placeholder="请输入内容" class="width-200">
          </el-input>
          <!-- 商品品牌 -->
          <el-select placeholder="选择商品品牌" v-model="defaultQuery.brandId" class="pad-l-10 width-150" clearable>
            <el-option v-for="(item, index) in brandList" :key="index" :label="item.brandName" :value="item.brandId">
            </el-option>
          </el-select>
          <!-- 商品分类 -->
          <el-cascader v-model="categoryIds" placeholder="选择商品分类" class="pad-l-10 width-260" :options="categoryData"
            :props="{ checkStrictly: true }" filterable clearable>
          </el-cascader>
          <el-select v-model="goodsSource" class="pad-l-10 width-200" placeholder="商品来源" clearable>
            <el-option label="总部自营" value="0"></el-option>
            <el-option label="淘宝联盟" value="2"></el-option>
            <el-option v-for="(item, index) in supplierList" :key="index" :label="item.supplierName"
              :value="item.supplierId"></el-option>
          </el-select>
          <el-button-group class="mar-l-20">
            <el-button type="primary" @click="doSearch">查询</el-button>
            <el-button plain @click="doResetSearch">重置</el-button>
          </el-button-group>
        </div>
      </div>

      <div v-if="tabActiveStatus != 0" class="mar-b-20">
        <div v-if="opeartModuleShowType === 4">
          <el-button @click="handleSynInventory">同步库存</el-button>
        </div>
        <div v-else-if="opeartModuleShowType === 1 || opeartModuleShowType === 2 || opeartModuleShowType === 3">
          <el-button @click="doOpenImport" type="primary">批量导入入库</el-button>
          <el-button v-if="warehouse.warehouseSource == 1" @click="openBatchPurchase" type="primary">批量采购</el-button>
          <el-button @click="openBatchStock" type="primary">批量入库</el-button>
          <!--        <template v-if="warehouse.warehouseType == 1">
            <el-button v-if="warehouse.warehouseSource == 1" @click="batPurchaseOrder" type="primary">批量采购</el-button>
          </template> -->
          <!-- <el-button v-if="warehouse.warehouseType == 2" @click="syncThirdGoods">同步商品</el-button> -->
          <!-- <el-button v-if="warehouse.warehouseType == 2" @click="syncThirdStock">同步库存</el-button> -->
          <el-button v-if="warehouse.warehouseType == 2" @click="synInventoryDialogVisible = true"
            :style="{ display: 'none' }">同步库存设置</el-button>
        </div>
      </div>

      <!-- 内容列表 -->
      <div class="table-container">
        <el-table :data="goodsList" @selection-change="handleSelectionChange" v-loading="listLoading"
          element-loading-text="加载中">
          <el-table-column width="50px" type="selection" fixed="left"></el-table-column>
          <el-table-column width="320px" label="商品" fixed="left">
            <template slot-scope="scope">
              <div class="flex v-align-c">
                <label><img :src="scope.row.mainImage" class="user-avatar"></label>
                <div class="font-14 pad-l-10 v-align-h">
                  <div class="line-2">
                    <el-tag size="mini" v-if="scope.row.skuFlag == 1" type="danger" effect="light">多</el-tag>
                    <span>{{scope.row.title}}</span>
                  </div>
                  <template v-if="scope.row.categoryName">
                    <span class="font-color-6 font-13">[{{scope.row.categoryName}}]</span>
                  </template>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column width="250px" label="商品货号" prop="goodsCode"></el-table-column>
          <el-table-column width="160px" label="商品品牌" prop="brandName"></el-table-column>
          <el-table-column width="180px" label="来源">
            <template slot-scope="scope">
              <span v-if="scope.row.goodsSource == 0">总部自营</span>
              <span v-if="scope.row.goodsSource == 1">{{scope.row.supplierName}}</span>
              <span v-if="scope.row.goodsSource == 2">淘宝联盟</span>
            </template>
          </el-table-column>
          <el-table-column width="140px" label="状态" prop="goodsStatus">
            <template slot-scope="scope">
              <span v-if="scope.row.goodsStatus == 1">已上架</span>
              <span v-if="scope.row.goodsStatus == 0">已下架</span>
            </template>
          </el-table-column>
          <el-table-column width="140px" label="当前库存">
            <template slot-scope="scope">
              <div>{{ scope.row.stock }}</div>
              <div class="font-green">可用：{{ scope.row.remainStock }}</div>
              <div>占用：{{ scope.row.stockInUse }}</div>
              <div>冻结：{{ scope.row.stockFrozen }}</div>
            </template>
          </el-table-column>
          <el-table-column width="140px" label="第三方编码" v-if="warehouse.warehouseType == 2">
            <template slot-scope="scope">
              <span v-if="scope.row.skuFlag == 1">
                <el-button type="text" size="medium" @click="getGoodsDetails(scope.row)">详见商品详情</el-button>
              </span>
              <span v-else>{{scope.row.thirdCode}}</span>
            </template>
          </el-table-column>
          <el-table-column min-width="240px" label="操作" fixed="right" align="right">
            <template slot-scope="scope">
              <el-button type="text" size="medium" @click="getGoodsDetails(scope.row)">查看详情</el-button>
              <template v-if="tabActiveStatus != 0">
                <template v-if="warehouse.warehouseType == 1">
                  <el-button v-if="warehouse.warehouseSource == 1" type="text" size="medium"
                    @click="openPurchaseOrder(scope.row)">采购</el-button>
                  <el-button type="text" size="medium" @click="openStockEdit(scope.row)">入库</el-button>
                </template>
                <template v-if="warehouse.warehouseType == 2">
                  <el-button type="text" size="medium" @click="syncThirdGoods(scope.row)">同步商品</el-button>
                  <el-button type="text" size="medium" @click="syncThirdStock(scope.row)">同步库存</el-button>
                  <el-button type="text" size="medium" @click="clearThirdWarehouseCode(scope.row)">清除第三方编码</el-button>
                </template>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 列表分页 -->
      <div class="pagination">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="searchListQuery.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="searchListQuery.size"
          layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>

      <!-- 批量导入入库dialog -->
      <el-dialog width="500px" title="批量导入入库" :visible.sync="batchImportVisible">
        <div v-loading="importLoading">
          <el-form :model="importForm" label-width="130px">
            <el-form-item label="导入文件：">
              <div v-if="importForm.importFileName">{{ importForm.importFileName }}</div>
              <el-upload name="files" action="/api/common/uploadFiles" :multiple="false" :show-file-list="false"
                :data="token" :before-upload="beforeUploadFile" :on-success="handleUploadSuccess">
                <el-button size="small" type="primary">选取文件</el-button>
              </el-upload>
              <span class="font-blue">
                <el-button @click="doExportGoods" type="text">点击导出待初始化商品数据</el-button>
              </span>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="doImport">确定</el-button>
            <el-button @click="batchImportVisible = false">取消</el-button>
          </div>
        </div>
      </el-dialog>

      <!-- 采购订单dialog -->
      <el-dialog v-if="purchaseOrderVisible" title="采购申请" :visible.sync="purchaseOrderVisible" width="580px">
        <purchase-order-form-page :showFlag="purchaseOrderVisible" :purchaseOrder="purchaseOrderForm"
          @callback="doCallbackPurchaseOrder"></purchase-order-form-page>
      </el-dialog>

      <!-- 入库商品dialog -->
      <el-dialog v-if="stockEditVisible" :visible.sync='stockEditVisible' width="580px">
        <warehouse-stock-edit :showFlag="stockEditVisible" :businessTypeList="['5']" :stockOrder="stockForm"
          @callback="doCloseEditStock"></warehouse-stock-edit>
      </el-dialog>

      <!-- 同步库存设置dialog -->
      <el-dialog width="800px" title="同步库存设置" :visible.sync="synInventoryDialogVisible">
        <synInventoryConfig :showFlag="synInventoryDialogVisible" @callback="doCallbackConfig"></synInventoryConfig>
      </el-dialog>

    </div>

  </div>
</template>

<script>
  import {
    pagingWarehouseGoods,
    doExportWarehouseGoods,
    syncWarehouseGoodsList,
    syncWarehouseGoodsStockList,
    syncWarehouseGoodsStockByDockingSystem
  } from '@/api/warehouse/warehouseGoods'
  import {
    batchImportGoods
  } from '@/api/warehouse/warehouseStock'
  import {
    listSupplier
  } from '@/api/user/supplier'
  import {
    listGoodsCategory
  } from '@/api/goods/goods'
  import {
    getToken
  } from '@/utils/auth'
  import {
    getWarehouse
  } from '@/api/warehouse/warehouseInfo'
  import {
    listBrand
  } from '@/api/user/enterpriseBrand'
  import warehouseStockEdit from '@/views/warehouse/components/warehouse-stock-edit'
  import purchaseOrderFormPage from '@/views/warehouse/components/purchase-order-form-page'
  import synInventoryConfig from '@/views/warehouse/components/syn-inventory-config'

  export default {
    components: {
      purchaseOrderFormPage,
      warehouseStockEdit,
      synInventoryConfig
    },
    data() {
      return {
        // tab model
        tabActiveStatus: '1',
        // 文本model
        textCol: 'title',
        textValue: '',
        // 查询条件
        searchListQuery: {},
        // 默认条件
        defaultQuery: {
          warehouseId: '',
          currentPage: 1,
          size: 10,
          brandId: ''
        },
        // 商品来源
        goodsSource: '',
        // 商品分类集合
        categoryIds: [],
        // 总记录数
        total: 0,
        multipleSelection: [],
        listLoading: false,
        // 入库单表单
        stockForm: {
          stockId: '',
          businessType: '5',
          supplierId: '',
          remark: '',
          warehouseGoodsIds: []
        },
        // 采购订单表单
        purchaseOrderForm: {
          purchaseOrderId: '',
          supplierId: '',
          consigneeProvinceCode: '',
          consigneeCityCode: '',
          consigneeDistrictCode: '',
          consigneeAddress: '',
          consignee: '',
          consigneePhone: '',
          remark: ''
        },
        // 返回的商品列表数据
        goodsList: [],
        // 商品品牌列表
        brandList: [],
        // 商品分类列表
        categoryData: [],
        // 供应商列表
        supplierList: [],
        // 导入的表单
        importForm: {},
        token: '',
        // 批量导入入库dialog
        batchImportVisible: false,
        // 采购商品dialog
        purchaseOrderVisible: false,
        // 入库商品dialog
        stockEditVisible: false,
        importLoading: false,
        warehouse: {
          warehouseType: 4
        },
        synInventoryDialogVisible: false,
        externalCodes: [],
        textarea: '',
        // 操作模块显示类型
        opeartModuleShowType: undefined
      }
    },
    created() {
      this.searchListQuery = {
        ...this.defaultQuery
      }
      this.token = {
        accessToken: getToken()
      }
      const enterpriseId = this.getEnterpriseId()
      // 获取商品分类
      listGoodsCategory(enterpriseId).then(response => {
        this.categoryData = response.data
      })
      // 获取品牌
      listBrand(enterpriseId).then(response => {
        if (response.isError) return
        this.brandList = response.data
      })
      // 获取供应商
      listSupplier({
        enterpriseId: enterpriseId
      }).then(response => {
        if (response.isError) return
        this.supplierList = response.data
      })
      // 获取仓库信息
      getWarehouse(this.getWarehouseId()).then((response) => {
        if (response.isError) return
        Object.assign(this.warehouse, response.data)
        this.opeartModuleShowType = this.warehouse.warehouseType
      })
      this.initList()
    },
    methods: {
      // tab 切换事件
      doChangeTab() {
        this.doSearch()
      },
      // 初始化商品列表
      initList() {
        this.listLoading = true
        const size = this.searchListQuery.size
        const currentPage = this.searchListQuery.currentPage
        this.searchListQuery = {
          ...this.defaultQuery
        }
        this.searchListQuery.size = size
        this.searchListQuery.currentPage = currentPage
        this.searchListQuery[this.textCol] = this.textValue
        this.searchListQuery.oneCategoryId = this.categoryIds.length > 0 ? this.categoryIds[0] : ''
        this.searchListQuery.twoCategoryId = this.categoryIds.length > 1 ? this.categoryIds[1] : ''
        this.searchListQuery.threeCategoryId = this.categoryIds.length > 2 ? this.categoryIds[2] : ''
        this.searchListQuery.warehouseId = this.getWarehouseId()
        if (this.tabActiveStatus === '2') {
          this.searchListQuery.stockZeroFlag = 1
          this.searchListQuery.authorizeStatus = 1
        } else {
          this.searchListQuery.authorizeStatus = this.tabActiveStatus
        }
        if (this.goodsSource !== '0' && this.goodsSource !== '2') {
          this.searchListQuery.supplierId = this.goodsSource
        } else {
          this.searchListQuery.goodsSource = this.goodsSource
        }
        pagingWarehouseGoods(this.searchListQuery).then(response => {
          this.listLoading = false
          if (response.isError) return
          this.total = response.data.total
          this.goodsList = response.data.records
        })
      },
      // 查看详情
      getGoodsDetails(row) {
        this.$router.push({
          path: '/goods/warehouse-goods-details/index',
          query: {
            warehouseGoodsId: row.warehouseGoodsId,
            supplierId: row.supplierId
          }
        })
      },
      // 查询事件
      doSearch() {
        this.searchListQuery.currentPage = 1
        this.initList()
      },
      // 重置事件
      doResetSearch() {
        const originData = this.$options.data()
        this.textCol = originData.textCol
        this.textValue = originData.textValue
        this.defaultQuery = originData.defaultQuery
        this.categoryIds = originData.categoryIds
        this.goodsSource = originData.goodsSource
        this.doSearch()
      },
      // 打开入库dialog
      openStockEdit(row) {
        Object.assign(this.stockForm, row)
        this.stockForm.disableSelectSupplier = true
        this.stockForm.supplierId = !row.supplierId ? '' : row.supplierId
        this.stockForm.warehouseGoodsIds = [row.warehouseGoodsId]
        this.stockEditVisible = true
      },
      // 打开采购dialog
      openPurchaseOrder(row) {
        Object.assign(this.purchaseOrderForm, row)
        this.purchaseOrderForm.supplierId = !row.supplierId ? '' : row.supplierId
        this.purchaseOrderForm.disableSelectSupplier = true
        this.purchaseOrderForm.warehouseGoodsIds = [row.warehouseGoodsId]
        this.purchaseOrderVisible = true
      },
      // 关闭出入库dialog事件
      doCloseEditStock() {
        this.stockEditVisible = false
      },
      // 关闭采购单dialog事件
      doCallbackPurchaseOrder() {
        this.purchaseOrderVisible = false
      },
      // 打开导入dialog
      doOpenImport() {
        this.importForm = {
          fileUrl: '',
          importFileName: ''
        }
        this.batchImportVisible = true
      },
      // 打开批量采购
      openBatchPurchase() {
        if (this.multipleSelection.length === 0) {
          this.$message({
            type: 'error',
            message: '请选择商品'
          })
          return
        }
        this.purchaseOrderForm.warehouseGoodsIds = this.multipleSelection.map(e => e.warehouseGoodsId)
        this.purchaseOrderForm.supplierId = ''
        this.purchaseOrderForm.disableSelectSupplier = true
        this.purchaseOrderVisible = true
      },
      // 打开批量入库dialog
      openBatchStock() {
        if (this.multipleSelection.length === 0) {
          this.$message({
            type: 'error',
            message: '请选择商品'
          })
          return
        }
        this.stockForm.warehouseGoodsIds = this.multipleSelection.map(e => e.warehouseGoodsId)
        this.stockForm.disableSelectSupplier = true
        this.stockForm.supplierId = ''
        this.stockEditVisible = true
      },
      batPurchaseOrder() {
        if (this.multipleSelection.length === 0) {
          this.$message({
            type: 'error',
            message: '请选择商品'
          })
          return
        }
        this.purchaseOrderForm.disableSelectSupplier = true
        this.purchaseOrderForm.supplierId = ''
        this.purchaseOrderForm.warehouseGoodsIds = this.multipleSelection.map(e => e.warehouseGoodsId)
        this.purchaseOrderVisible = true
      },
      // 文件上传前校验事件
      beforeUploadFile(file) {
        const ext = file.name.substring(file.name.lastIndexOf('.') + 1)
        if (ext !== 'xlsx') {
          this.$message.error('请上传xlsx格式的Excel')
          return false
        }
        this.importLoading = true
        return true
      },
      // 上传成功后事件
      handleUploadSuccess(res, file) {
        this.importLoading = false
        if (res.code !== 101) {
          this.$message.error(res.msg)
          return
        }
        this.importForm = {
          importFileName: file.name,
          fileUrl: res.data[0]
        }
        this.$message({
          type: 'success',
          message: '文件已上传'
        })
      },
      // 导出初始化商品数据
      doExportGoods() {
        window.open(doExportWarehouseGoods(this.getWarehouseId()), '_blank')
      },
      // 导入事件
      doImport() {
        if (!this.importForm.importFileName || !this.importForm.fileUrl) {
          this.$message({
            type: 'error',
            message: '请先上传文件'
          })
          return
        }
        this.importLoading = true
        this.importForm['warehouseId'] = this.getWarehouseId()
        batchImportGoods(this.importForm).then(response => {
          this.importLoading = false
          if (response.isError) return
          this.batchImportVisible = false
          this.initList()
          this.$message({
            type: 'success',
            message: '导入成功'
          })
        })
      },
      // 更改当前页数
      handleCurrentChange(val) {
        this.searchListQuery.currentPage = val
        this.initList()
      },
      // 更改当前页面大小
      handleSizeChange(val) {
        this.searchListQuery.size = val
        this.initList()
      },
      // 勾选
      handleSelectionChange(val) {
        this.multipleSelection = val
        if (this.multipleSelection.length === this.goodsList.length) {
          this.allChecked = true
        } else {
          this.allChecked = false
        }
      },
      syncThirdGoods(row) {
        syncWarehouseGoodsList({
          syncAll: !row ? 1 : 0,
          warehouseId: this.getWarehouseId(),
          warehouseGoodsId: !row ? '' : row.warehouseGoodsId
        }).then(response => {
          if (response.isError) return
          this.externalCodes = response.data
          if (this.externalCodes.length > 0) {
            let textarea = `<strong>同步商品中存在同步失败的商品</br></strong>`
            for (let a = 0; a < this.externalCodes.length; a++) {
              textarea += this.externalCodes[a] + `</br>`
            }
            textarea += `<strong>请确认后重新同步。</strong>`
            this.$alert(textarea, {
              dangerouslyUseHTMLString: true
            })
          }
          if (this.externalCodes.length === 0) {
            this.$message({
              type: 'success',
              message: '成功'
            })
          }
        })
      },
      syncThirdStock(row) {
        syncWarehouseGoodsStockList({
          syncAll: !row ? 1 : 0,
          warehouseId: this.getWarehouseId(),
          warehouseGoodsId: !row ? '' : row.warehouseGoodsId
        }).then(response => {
          if (response.isError) return
          this.$message({
            type: 'success',
            message: '成功'
          })
        })
      },
      clearThirdWarehouseCode() {
        const content = []
        content.push(this.$createElement('p', null, '清除第三方仓库编码可能会导致商品库存、单据同步失败。'))
        content.push(this.$createElement('br'))
        content.push(this.$createElement('p', null, '此功能一般用于当前商品下所有SKU均在第三方仓库系统中已被删除的场景。'))
        content.push(this.$createElement('br'))
        this.$confirm('提示', {
          message: this.$createElement('div', null, content),
          confirmButtonText: '确定要清除',
          cancelButtonText: '取消',
          type: 'warning',
          customClass: 'confirm-width-600'
        }).then(() => {}).catch(() => {})
      },
      // 商品库存同步设置回调事件
      doCallbackConfig() {
        this.synInventoryDialogVisible = false
      },
      // 同步库存
      handleSynInventory() {
        var goodsIds = []
        if (this.multipleSelection && this.multipleSelection.length > 0) {
          this.multipleSelection.forEach(e => {
            goodsIds.push(e.goodsId)
          })
        }
        this.$confirm('确定要同步库存吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const loading = this.$loading({
            lock: true,
            text: '同步库存中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          syncWarehouseGoodsStockByDockingSystem(this.getWarehouseId(), goodsIds).then(response => {
            loading.close()
            if (response.isError) return
            this.msgSuccess(response.msg)
            this.initList()
          })
        }).catch(() => {})
      }
    }
  }
</script>

<style lang="less" scoped>
  .user-avatar {
    width: 65px;
    height: 65px;
    display: block;
    padding: 1px;
    border: #efefef 1px solid;
  }

  // 2行文字展示
  .line-2 {
    line-height: 1.4;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    word-break: break-word;
  }
</style>
<style lang="less">
  .confirm-width-600 {
    width: 600px;
  }
</style>
